<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!-- <el-form-item label="投票名称" prop="voteId">
        <el-select placeholder="请输入关键词" @change="changeVote" v-model="queryParams.voteId" style="width: 240px">
          <el-option v-for="vote in voteNameList" :key="vote.id" :label="vote.voteName" :value="vote.id"/>
        </el-select>
      </el-form-item> -->
      <el-form-item label="投票名称" >
        <el-select
         style="width:180px;"
          v-model="queryParams.voteName"
          filterable
          remote
          reserve-keyword
          @change="changeVote"
          placeholder="请输入关键词"
          :remote-method="remoteSelectMethod"
         >
          <el-option
            v-for="item in voteNameList"
            :key="item.id"
            :label="item.voteName"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="queryParams.mobile" placeholder="请输入手机号" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="用户名称" prop="userName">
        <el-input v-model="queryParams.userName" placeholder="请输入用户名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <!-- <el-form-item label="是否领导投票" prop="isManager">
        <el-input v-model="queryParams.isManager" placeholder="请输入是否领导投票" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['vote:user-result:create']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" icon="el-icon-upload2" size="mini" @click="handleImport"
                    v-hasPermi="['vote:user-result:import']">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" :loading="exportLoading"
                   v-hasPermi="['vote:user-result:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="list">
      <el-table-column label="投票名称" align="center" prop="voteName" />
      <el-table-column label="所在组" align="center" prop="groupName" />
      <el-table-column label="所在单位" align="center" prop="unitName" />
      <el-table-column label="手机号" align="center" prop="mobile" />
      <el-table-column label="用户名称" align="center" prop="userName" />
      <el-table-column label="优秀" align="center" prop="excellent" />
      <el-table-column label="合格" align="center" prop="qualified" />
      <el-table-column  label="基本合格" align="center" prop="baseQualified" />
      <el-table-column  label="不合格" align="center" prop="unqualified" />
      <el-table-column  label="弃权" align="center" prop="waiver" />
      <el-table-column label="投票人数" align="center" prop="total" />
      <el-table-column label="权重" align="center" prop="weight" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['vote:user-result:update']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['vote:user-result:delete']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="投票名称" prop="voteId">
           <el-select disabled placeholder="请输入关键词" @change="changeVote" v-model="form.voteId" style="width: 240px">
            <el-option v-for="vote in voteNameList" :key="vote.id" :label="vote.voteName" :value="vote.id"/>
           </el-select>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="form.mobile" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="用户名称" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入用户名称" />
        </el-form-item>
        <el-form-item label="所在单位" prop="unitName">
          <el-input v-model="form.unitName" placeholder="所在单位" />
        </el-form-item>
        <!-- <el-form-item label="量化分" prop="quantifiedScore">
          <el-input v-model="form.quantifiedScore" placeholder="请输入量化分" />
        </el-form-item> -->
        <!-- <el-form-item label="投票人数" prop="total">
          <el-input v-model="form.total" placeholder="请输入投票人数" />
        </el-form-item> -->
        <el-form-item label="权重" prop="weight">
          <el-input-number v-model="form.weight" :min="1"  placeholder="请输入权重">10</el-input-number>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport +'&voteId='+upload.voteId" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的投票用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { createUserResult, updateUserResult, deleteUserResult, getUserResult, getUserResultPage, exportUserResultExcel,importTemplate } from "@/api/vote/userResult";
import { getVoteName } from "@/api/vote/info";
import {getBaseHeader} from "@/utils/request";
import {DICT_TYPE, getDictDatas} from "@/utils/dict";
export default {
  name: "VoteTypeYear",
  components: {
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 投票结果列表
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      dateRangeCreateTime: [],
      // 投票名称
      voteNameList: [],
      // 类型
      voteType : "2",

      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        userId: null,
        voteId: null,
        voteName: null,
        mobile: null,
        userName: null,
        excellentMgr: null,
        excellent: null,
        qualifiedMgr: null,
        qualified: null,
        baseQualifiedMgr: null,
        baseQualified: null,
        unqualifiedMgr: null,
        unqualified: null,
        waiverMgr: null,
        waiver: null,
        quantifiedScore: null,
        total: null,
        weight: null,
        remark: null,
        isSave: null,
        isManager: null,
        voteType: 2,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userName: [
          { required: true, message: "姓名不能为空", trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "手机号", trigger: "blur" },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ],
      },
      //用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: getBaseHeader(),
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/admin-api/vote/user-result/import'
      },
      voteTypeDictDatas: getDictDatas(DICT_TYPE.VOTE_RULE_TYPE),
    };
  },
  created() {
    this.getVote();
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 处理查询参数
      let params = {...this.queryParams};
      this.addBeginAndEndTime(params, this.dateRangeCreateTime, 'createTime');
      // 执行查询
      getUserResultPage(params).then(response => {
        this.list = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    getVote(query) {
      let params = {...this.queryParams};
      if(query){
        params.vateName = query;
      }
      getVoteName(params).then(response => {
        this.voteNameList = response.data;
        if(this.voteNameList!=null && this.voteNameList.length>0){
          this.upload.voteId = this.voteNameList[0].id;
          this.queryParams.voteId = this.voteNameList[0].id;
          this.queryParams.voteName = this.voteNameList[0].voteName;
        }
        this.getList();
      });
     
    },
    remoteSelectMethod(query){
      let params = {
        voteName: query,
        voteType: this.queryParams.voteType,
        pageSize: 10,
        pageNo: 1
      };
      getVoteName(params).then(response => {
        this.voteNameList = response.data;
      });
    },
    changeVote(query){
        this.upload.voteId =query;
        this.queryParams.voteId = query;
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        userId: undefined,
        voteId: undefined,
        voteName: undefined,
        mobile: undefined,
        userName: undefined,
        excellentMgr: undefined,
        excellent: undefined,
        qualifiedMgr: undefined,
        qualified: undefined,
        baseQualifiedMgr: undefined,
        baseQualified: undefined,
        unqualifiedMgr: undefined,
        unqualified: undefined,
        waiverMgr: undefined,
        waiver: undefined,
        quantifiedScore: undefined,
        total: undefined,
        weight: 10,
        remark: undefined,
        isSave: undefined,
        isManager: undefined,
      };
      this.resetForm("form");
      this.form.voteId = this.queryParams.voteId;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRangeCreateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加投票结果";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getUserResult(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改投票结果";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }
        // 修改的提交
        if (this.form.id != null) {
          updateUserResult(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
          return;
        }
        // 添加的提交
        createUserResult(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal.confirm('是否确认删除投票结果编号为"' + id + '"的数据项?').then(function() {
          return deleteUserResult(id);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = {...this.queryParams};
      params.pageNo = undefined;
      params.pageSize = undefined;
      this.addBeginAndEndTime(params, this.dateRangeCreateTime, 'createTime');
      // 执行导出
      this.$modal.confirm('是否确认导出所有投票结果数据项?').then(() => {
          this.exportLoading = true;
          return exportUserResultExcel(params);
        }).then(response => {
          this.$download.excel(response, '投票结果.xls');
          this.exportLoading = false;
        }).catch(() => {});
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "投票人员导入";
      this.upload.open = true;
    },
     /** 下载模板操作 */
    importTemplate() {
      importTemplate().then(response => {
        this.$download.excel(response, '投票人员模板.xls');
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      if (response.code !== 0) {
        this.$modal.msgError(response.msg)
        return;
      }
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      // 拼接提示语
      let data = response.data;
      let text = '创建成功数量：' + data.createUsernames.length;
      // for (const username of data.createUsernames) {
      //   text += '<br />&nbsp;&nbsp;&nbsp;&nbsp;' + username;
      // }
      text += '<br />更新成功数量：' + data.updateUsernames.length;
      // for (const username of data.updateUsernames) {
      //   text += '<br />&nbsp;&nbsp;&nbsp;&nbsp;' + username;
      // }
      text += '<br />更新失败数量：' + Object.keys(data.failureUsernames).length;
      for (const username in data.failureUsernames) {
        text += '<br />&nbsp;&nbsp;&nbsp;&nbsp;' + username + '：' + data.failureUsernames[username];
      }
      this.$alert(text, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      if(this.upload.voteId==null){
        return this.$modal.msgSuccess("请先选择投票规则");
      }
      this.$refs.upload.submit();
    },
    handleNodeClick(tab){
      console.log("tab",tab)
      this.queryParams.voteType = tab.name;
      this.queryParams.vateId = null;
      this.queryParams.vateName = null;
      this.getVote();
    }
  }
};
</script>
